package com.fessc.develop.handler.processor.request;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fessc.develop.base.CCBResult;
import com.fessc.develop.entity.dbvo.TAccountSynchron;
import com.fessc.develop.entity.ccbvo.CCBResponseBodyVo;
import com.fessc.develop.entity.ccbvo.CCBResponseHeadVo;
import com.fessc.develop.entity.dbvo.TOrgUrlManage;
import com.fessc.develop.handler.SignHandler;
import com.fessc.develop.model.enums.*;
import com.fessc.develop.service.interfaces.ITAccountSynchronService;
import com.fessc.develop.service.interfaces.ITOrgUrlManageService;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.DateUtil;
import com.fessc.develop.utils.ExceptionUtil;
import com.fessc.develop.utils.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@Service
public class CCBAccountSyncService implements CCBIBaseService {

    @Resource
    private SignHandler signHandler;

    @Resource
    private ITOrgUrlManageService tOrgUrlManageService;

    @Resource
    private ITAccountSynchronService identityVerifyServiceImpl;

    @Resource
    private OkHttpUtil okHttpUtil;

    @Override
    public String getServiceCode() {
        return EnumServiceCode.CCB_HMT002.toString();
    }

    @Override
    public CCBResult<CCBResponseBodyVo> process(String requestBody) {
        log.info("HMT002接口请求报文: " + requestBody);
        JSONObject jsonObject = JSONObject.parseObject(requestBody);
        String signType = jsonObject.getJSONObject("body").getString("SignTp");
        CCBResult<CCBResponseBodyVo> result = new CCBResult<>();
        switch (signType) {
            case "1":
                //todo:同步边民开户信息至市场交易平
                result = accountSynchron(jsonObject);
                break;
            case "2":
                //todo:同步商铺开户信息至市场交易平
                result = accountSynchron(jsonObject);
                break;
            default:
                //todo:报错
                throw ExceptionUtil.businessException("EE4013");
        }
        return result;
    }

    /**
     * 更新市场交易平台边民、商铺开户信息
     */
    private CCBResult<CCBResponseBodyVo> accountSynchron(JSONObject jsonObject) {
        String CoPlfID = jsonObject.getJSONObject("head").getString("CoPlfID");
        String reqTraceId = BusiUtil.nvl(jsonObject.getJSONObject("head").getString("ReqTraceId"), UUID.randomUUID().toString());
        JSONObject json = new JSONObject();

        //组装发送公共交易中心报文head
        JSONObject jsonSysHead = new JSONObject();
        jsonSysHead.put("SERVICE_CODE", EnumServiceCode.IDENTITY_TP0002.toString());
        jsonSysHead.put("TRAN_DATE", DateUtil.getCurrentDateTime(DateUtil.DATE_SIMP_FORMAT));
        jsonSysHead.put("TRAN_TIMESTAMP", DateUtil.getCurrentDateTime(DateUtil.DATE_TIME_HM_FORMAT));
        jsonSysHead.put("CHANNEL_SEQ_NO", reqTraceId);

        //组装发送公共交易中心报文body
        JSONObject jsonBodyHead = new JSONObject();
        jsonBodyHead.put("SignTp", jsonObject.getJSONObject("body").getString("SignTp"));
        jsonBodyHead.put("Name", jsonObject.getJSONObject("body").getString("Name"));
        jsonBodyHead.put("CrdtTp", jsonObject.getJSONObject("body").getString("CrdtTp"));
        jsonBodyHead.put("CrdtNo", jsonObject.getJSONObject("body").getString("CrdtNo"));
        jsonBodyHead.put("Nat", jsonObject.getJSONObject("body").getString("Nat"));
        jsonBodyHead.put("AccNo", jsonObject.getJSONObject("body").getString("AccNo"));
        jsonBodyHead.put("BnkCd", jsonObject.getJSONObject("body").getString("BnkCd"));
        jsonBodyHead.put("Tel", jsonObject.getJSONObject("body").getString("Tel"));
        jsonBodyHead.put("OvseaInd", jsonObject.getJSONObject("body").getString("OvseaInd"));
        jsonBodyHead.put("SignInd", jsonObject.getJSONObject("body").getString("SignInd"));
        json.put(EnumJsonProperty.REQ_SYS_HEAD.toString(), jsonSysHead);
        json.put(EnumJsonProperty.REQ_BODY.toString(), jsonBodyHead);
        log.info("边民商铺开户信息同步发送报文明文： " + json.toJSONString());

        //根据机构查询配置表获取URL,通用默认一个机构只有一个URL
        TOrgUrlManage tOrgUrlManage = tOrgUrlManageService.getOrgUrlByOrgCodeAndKey(CoPlfID, EnumOrgType.OTHER.toString(), EnumServiceCode.IDENTITY_TP0001.toString());
        String afterEncrypt = signHandler.encrypt(jsonBodyHead.toString(), tOrgUrlManage.getPubCert());
        json.put(EnumJsonProperty.REQ_SYS_HEAD.toString(), jsonSysHead);
        json.put(EnumJsonProperty.REQ_BODY.toString(), afterEncrypt);
        log.info("边民商铺开户信息同步发送报文密文：" + json.toJSONString());

        // 发送市场交易平台同步开户信息
        String response = "";
        String afterDecrypt = "";
        JSONObject responseBody = null;
        try {
            // 先解析返回json
            response = okHttpUtil.doPostJson(tOrgUrlManage.getInterfaceUrl(), json.toJSONString());
            responseBody = JSON.parseObject(response);
            String date = responseBody.getString(EnumJsonProperty.RES_DATA.toString());
            log.info("市场交易平台响应报文(解密前): " + responseBody);
            // 解析DATA部分
            afterDecrypt = signHandler.decrypt(date);
            responseBody.put(EnumJsonProperty.RES_DATA.toString(), JSON.parseObject(afterDecrypt));
            log.info("市场交易平台响应报文(解密后): " + responseBody);
        } catch (Exception e) {
            log.info("市场交易平台信息反馈响应报文解析失败: " + e.getMessage());
        }
        CCBResult<CCBResponseBodyVo> result = new CCBResult<>(EnumResultType.CCB_SUCCESS.getStatusCode(), EnumResultType.CCB_SUCCESS.getMsg());
        CCBResponseHeadVo headVo = new CCBResponseHeadVo();
        CCBResponseBodyVo bodyVo = new CCBResponseBodyVo();
        headVo.setReqtraceid(reqTraceId);
        headVo.setMsgbsntp(EnumServiceCode.CCB_HMT002.toString());
        headVo.setOrg(jsonObject.getJSONObject("head").getString("Org"));
        headVo.setCoplfid(jsonObject.getJSONObject("head").getString("CoPlfID"));
        String PcsgRlt = Objects.requireNonNull(responseBody).getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("PcsgRlt");
        String FalRs = responseBody.getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("FalRs");
        if (BusiUtil.isEquals(PcsgRlt, EnumResultType.CCB_SUCCESS.getStatusCode())) {
            bodyVo.setPsgrlt(EnumResultType.CCB_VERIFY_SUCCESS.getStatusCode());
        } else {
            bodyVo.setPsgrlt(EnumResultType.CCB_VERIFY_FAIL.getStatusCode());
            bodyVo.setFalrs(BusiUtil.nvl(FalRs, "处理失败"));
        }
        result.setHead(headVo);
        result.setBody(bodyVo);

        //保存银行反馈边民商铺开户信息
        try {
            log.info("保存银行同步边民商铺开户信息：");
            TAccountSynchron dentitySynchron = new TAccountSynchron();
            dentitySynchron.setSignType(jsonObject.getJSONObject("body").getString("SignTp"));
            dentitySynchron.setName(jsonObject.getJSONObject("body").getString("Name"));
            dentitySynchron.setCardType(jsonObject.getJSONObject("body").getString("CrdtTp"));
            dentitySynchron.setCardNo(jsonObject.getJSONObject("body").getString("CrdtNo"));
            dentitySynchron.setNat(jsonObject.getJSONObject("body").getString("Nat"));
            dentitySynchron.setAccountNo(jsonObject.getJSONObject("body").getString("AccNo"));
            dentitySynchron.setBankCode(jsonObject.getJSONObject("body").getString("BnkCd"));
            dentitySynchron.setTel(jsonObject.getJSONObject("body").getString("Tel"));
            dentitySynchron.setOvseaInd(jsonObject.getJSONObject("body").getString("OvseaInd"));
            dentitySynchron.setSignInd(jsonObject.getJSONObject("body").getString("SignInd"));
            dentitySynchron.setRequestTime(DateUtil.getCurrentLocalDateTime());
            dentitySynchron.setOrgCode(CoPlfID);
            dentitySynchron.setResponseCode(responseBody.getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("PcsgRlt"));
            dentitySynchron.setResponseLog(responseBody.getJSONObject(EnumJsonProperty.RES_DATA.toString()).getString("FalRs"));
            identityVerifyServiceImpl.save(dentitySynchron);
        } catch (Exception e) {
            log.info("保存银行同步边民商铺开户信息失败: " + e.getMessage());
        }
        return result;
    }
}
